<!-- #layout name=default -->
<div id="main" class="fixed" v-cloak>
  <div class="page-header" style="min-width: 920px">
    <template v-if="isNewCode">
      <div class="form-inline pull-left margin-right-10">
        <div class="form-group">
          <h1 class="title pull-left">{{Kooboo.text.common.Code + ': '}}</h1>
          <input
            @input="nameIsPolluted=!!$event.target.value"
            v-model="name"
            v-kb-hint="nameValidateModel.msg"
            type="text"
            placeholder="Name"
            class="form-control input-medium"
            data-container="body"
          />
        </div>
      </div>
    </template>
    <template v-else>
      <h1 class="title pull-left"
        >Script<span>:</span>
        <strong :title="name">{{name}}</strong>
      </h1>
    </template>

    <div class="form-inline pull-left" v-if="needUrl">
      <div class="form-group">
        <h1 class="title pull-left">URL</h1>
        <input
          v-model="url"
          type="text"
          placeholder="URL"
          v-kb-hint="urlValidateModel.msg"
          class="form-control input-medium"
        />
      </div>
    </div>

    <div class="col-md-5 pull-right row">
      <div class="col-md-2 pull-right">
        <button @click="formatCode" type="button" class="btn btn-default"
          >Format code</button
        >
      </div>
      <div class="form-inline pull-right">
        <template v-if="isNewCode">
          <div class="form-group">
            <select
              class="form-control"
              v-model="codeType"
              v-kb-hint:left="codeTypeValidateModel.msg"
            >
              <option v-for="item in availableCodeType" :value="item.value"
                >{{item.displayText}}</option
              >
            </select>
          </div>
          <!--    codeType.toLowerCase() === 'event' -->
          <div
            class="form-group"
            v-if="codeType && codeType.toLowerCase() === 'event'"
          >
            <select class="form-control" v-model="eventType">
              <option v-for="item in availableEventType" :value="item.value"
                >{{item.displayText}}</option
              >
            </select>
          </div>
        </template>
        <template v-else>
          <div class="form-group">
            <label for="">Code type:</label>
            <p class="form-control-static">
              <label for="" class="label label-sm green">{{codeType}}</label>
            </p>
          </div>
          <div
            class="form-group"
            v-if="codeType && codeType.toLowerCase() == 'event'"
          >
            <label for="">Event type:</label>
            <p class="form-control-static">
              <label for="" class="label label-sm label-success"
                >{{eventType}}</label
              >
            </p>
          </div>
        </template>
      </div>
    </div>
  </div>

  <div class="block-fullpage with-buttons">
    <div class="block-visual-editor default">
      <div class="tabs-bottom">
        <div class="tab-content">
          <div class="tab-pane" :class="{'active': activeTab === 'code'}">
            <div class="kb-editor">
              <kb-code-editor
                ref="code"
                :auto-size="true"
                :code.sync="codeContent"
                :lang="lang"
              ></kb-code-editor>
            </div>
          </div>
          <div class="tab-pane" :class="{'active': activeTab === 'config'}">
            <div class="kb-editor">
              <kb-code-editor
                ref="config"
                :auto-size="true"
                :code.sync="configContent"
                :lang="lang"
              ></kb-code-editor>
            </div>
          </div>
        </div>

        <ul class="nav nav-tabs">
          <li
            :class="activeTab == 'code' && 'active'"
            @click="activeTab='code'"
          >
            <a href="javascript:;">Code</a>
          </li>
          <li
            :class="activeTab == 'config' && 'active'"
            @click="activeTab='config'"
          >
            <a href="javascript:;">Config</a>
          </li>
        </ul>
      </div>

      <div class="kb-panel">
        <iframe
          src="/_Admin/Development/KScript/Documentation"
          frameborder="0"
          style="width: 410px; height: 100%"
        ></iframe>
      </div>
    </div>
  </div>

  <div class="page-buttons">
    <div class="btn-group dropup">
      <button @click="onSaveAndReturn" class="btn green" style="margin: 0"
        >Save & Return</button
      >
      <a
        class="btn green dropdown-toggle"
        data-toggle="dropdown"
        style="margin: 0; min-width: auto"
        ><i class="fa fa-angle-up"></i
      ></a>
      <ul class="dropdown-menu" role="menu">
        <li><a @click="onSave">Save</a></li>
      </ul>
    </div>
    <a @click.stop="onCancel" class="btn gray">Cancel</a>
  </div>
</div>
<script>
  (function () {
    Kooboo.loadJS([
      "/_Admin/Scripts/kooboo/Guid.js",
      "/_Admin/Scripts/components/kb-code-editor.js",
    ]);

    var self;
    new Vue({
      el: "#main",
      data: function () {
        return {
          isNewCode: false,
          codeId: Kooboo.getQueryString("Id") || Kooboo.Guid.Empty,
          name: undefined,
          codeContent: "",
          compareTarget: "",
          sourceChange: false,
          supportExtensions: undefined,
          codeChange: false,
          urlValidateModel: { valid: true, msg: "" },
          nameValidateModel: { valid: true, msg: "" },
          codeTypeValidateModel: { valid: true, msg: "" },
          lang: "javascript",
          codeType: undefined,
          eventType: undefined,
          url: undefined,
          configContent: undefined,
          availableCodeType: undefined,
          availableEventType: undefined,
          activeTab: "code",
          nameIsPolluted: false,
        };
      },
      watch: {
        codeContent: function (value) {
          if (value !== self.compareTarget) {
            self.codeChange = true;
          } else {
            self.codeChange = false;
          }
        },
        name: function () {
          self.nameValidateModel = { valid: true, msg: "" };
        },
        codeType: function () {
          self.codeTypeValidateModel = { valid: true, msg: "" };
        },
        url: function (value) {
          self.urlValidateModel = { valid: true, msg: "" };
          if (
            self.isNewCode &&
            !self.nameIsPolluted &&
            typeof value == "string"
          ) {
            value = value.replace(/(?!\w)./g, "_");

            while (value.startsWith("_")) {
              value = value.substr(1);
            }

            while (value.endsWith("_")) {
              value = value.substr(0, value.length - 1);
            }

            self.name = value;
          }
        },
      },
      created: function () {
        self = this;
        if (self.codeId === Kooboo.Guid.Empty) {
          self.isNewCode = true;
        }
        self.init();
      },
      mounted: function () {
        $(document).keydown(function (e) {
          if (e.keyCode == 83 && e.ctrlKey) {
            //Ctrl + S
            e.preventDefault();
            self.onSave();
          }
        });
      },
      methods: {
        init: function () {
          Kooboo.Code.getEdit({
            Id: self.codeId,
            codeType: Kooboo.getQueryString("codeType") || "all",
          }).then(function (res) {
            if (res.success) {
              self.name = res.model.name;
              self.codeContent = res.model.body || "";
              self.compareTarget = self.codeContent;
              self.url = res.model.url;

              if (res.model.availableCodeType) {
                self.availableCodeType = res.model.availableCodeType.map(
                  function (item) {
                    return {
                      displayText: item,
                      value: item.toLowerCase(),
                    };
                  }
                );
                self.availableCodeType.splice(0, 0, {
                  displayText: Kooboo.text.site.code.chooseCodeType,
                  value: undefined,
                });
              } else {
                self.availableCodeType = [];
                self.codeType = res.model.codeType;
              }

              if (res.model.availableCodeType) {
                self.availableEventType = res.model.availableEventType.map(
                  function (item) {
                    return {
                      displayText: item,
                      value: item,
                    };
                  }
                );
                if (
                  self.availableEventType.length &&
                  self.availableEventType[0].value
                ) {
                  self.eventType = self.availableEventType[0].value;
                }
                var codeTypeParams = Kooboo.getQueryString("codeType"),
                  eventTypeParma = Kooboo.getQueryString("eventType");

                if (codeTypeParams) {
                  self.codeType = codeTypeParams.toLowerCase();
                }
                if (eventTypeParma) {
                  self.codeType = "event";
                  self.eventType = eventTypeParma;
                }
              } else {
                self.availableEventType = [];
                self.eventType = res.model.eventType;
              }

              self.configContent = res.model.config || "";
            }
          });
        },
        formatCode: function () {
          this.$refs[this.activeTab].formatCode();
        },
        onSaveAndReturn: function () {
          self.onSubmitCode(function (model) {
            self.goBack();
          });
        },
        onSave: function () {
          self.onSubmitCode(function (id) {
            if (self.isNewCode) {
              location.href = Kooboo.Route.Get(Kooboo.Route.Code.EditPage, {
                Id: id,
              });
            } else {
              window.info.show(Kooboo.text.info.save.success, true);
              self.compareTarget = self.codeContent;
            }
          });
        },
        onCancel: function () {
          if (self.codeChange) {
            if (confirm(Kooboo.text.confirm.beforeReturn)) {
              self.goBack();
            }
          } else {
            self.goBack();
          }
        },
        goBack: function () {
          location.href = Kooboo.Route.Get(Kooboo.Route.Code.ListPage);
        },
        validate: function () {
          var urlRule = [
            { required: true, message: Kooboo.text.validation.required },
          ];
          var nameRule = [
            {
              required: true,
              message: Kooboo.text.validation.required,
            },
            {
              pattern: /^([A-Za-z][\w\-\.]*)*[A-Za-z0-9]$/,
              message: Kooboo.text.validation.objectNameRegex,
            },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64,
            },
            {
              remote: {
                url: Kooboo.Code.isUniqueName(),
                data: function () {
                  return { name: self.name };
                },
              },
              message: Kooboo.text.validation.taken,
            },
          ];
          var codeTypeRule = [
            {
              required: true,
              message: Kooboo.text.validation.required,
            },
          ];
          self.nameValidateModel = Kooboo.validField(self.name, nameRule);
          self.codeTypeValidateModel = Kooboo.validField(
            self.codeType,
            codeTypeRule
          );
          if (self.codeType && self.codeType === "api") {
            self.urlValidateModel = Kooboo.validField(self.url, urlRule);
            return (
              self.nameValidateModel.valid &&
              self.codeTypeValidateModel.valid &&
              self.urlValidateModel.valid
            );
          }
          return (
            self.nameValidateModel.valid && self.codeTypeValidateModel.valid
          );
        },
        onSubmitCode: function (callback) {
          if ((self.isNewCode && self.validate()) || !self.isNewCode) {
            Kooboo.Code.post({
              Id: self.isNewCode ? Kooboo.Guid.Empty : self.codeId,
              name: self.name,
              body: self.codeContent,
              config: self.configContent,
              codeType: self.codeType,
              eventType: self.eventType,
              url: self.needUrl ? self.url : "",
            }).then(function (res) {
              if (res.success) {
                callback &&
                  typeof callback == "function" &&
                  callback(res.model);
              } else {
                window.info.show(Kooboo.text.info.save.fail, false);
              }
            });
          }
        },
      },
      computed: {
        needUrl: function () {
          if (!this.codeType) return false;
          var type = this.codeType.toLowerCase();
          return type === "api";
        },
      },
    });
  })();
</script>
